home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 7953 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.6 KB  |  61 lines

  1. Path: news.itd.umich.edu!not-for-mail
  2. From: jlthomas@umd.umich.edu (Jeffrey L. Thomas)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: How to get program using Fork() and Pipe()
  5. Date: 29 Feb 1996 16:27:17 -0500
  6. Organization: Univerisity of Michigan - Dearborn
  7. Message-ID: <4h55nl$qga@null.umd.umich.edu>
  8. References: <4gic02$6l0@news.mty.itesm.mx>
  9. NNTP-Posting-Host: null.umd.umich.edu
  10. NNTP-Posting-User: jlthomas
  11. X-Newsreader: NN version 6.5.0 #3 (NOV)
  12.  
  13. al535994@academ10.mty.itesm.mx (ARTURO RAFAEL LOPEZ CASTRO) writes:
  14.  
  15. >I would like to know if someone could give program examples using fork and pipe because I have trouble using them.
  16.  
  17. >Thanks.
  18.  
  19.  
  20. int fork_off(prog)
  21.     char *prog;
  22. {
  23.     int ipd[2], opd[2], pid;
  24.  
  25.     /* making the input and output pipes */
  26.     if (pipe(ipd)<0 || pipe(opd)) { perror("pipe"); return(1); }
  27.  
  28.     if ((pid= fork())<0) { perror("pipe"); return(1); }
  29.  
  30.     if (pid==0) { /* exec the program */
  31.         dup2(ipd[1],1); /* resetting stdin and stdout for child */
  32.         dup2(opd[0],0);
  33.         execlp("prog", "prog", NULL);
  34.         /* this line only get executed on error */
  35.         perror("exec"); exit(1);
  36.     }
  37.  
  38.     dup2(ipd[0],0); /* resetting stdin and stdout for the parent */
  39.     dup2(opd[1],1);
  40.  
  41.     return(0);
  42. }
  43.  
  44.  
  45. and in your main program
  46.  
  47. ...
  48. char prog[]= "some_program";
  49. ...
  50. if (fork_off(prog)!=0) exit(1);
  51.  
  52. /*
  53.  * now stdin if comming in from the program and stdout is going to the program
  54.  */
  55.  
  56. -- 
  57. \|||/  _Spike_Man_      ____  | Jeffery L. Thomas  | "The important thing is
  58.  ^.^  The Internet's   /    \ | jlthomas@umich.edu | not to stop questioning.
  59.   v   first superhero  \ SM / | "This time it will | Curiosity has it own
  60. "more than a cute .sig" \__/  | surely run" - anon | reason for existing."
  61.